package ru.ifmo.ctddev.krotkov.taskrunner;

import java.util.ArrayDeque;

public class TaskRunnerImpl implements TaskRunner {
	ArrayDeque<MyTask<?, ?>> q;
	Thread[] threads;

	public <X, Y> X run(Task<X, Y> task, Y value) {
		MyTask<X, Y> t = new MyTask<X, Y>(task, value);
		synchronized (q) {
			q.add(t);
			//System.err.println(q.size());
			q.notify();
		}
		try {
			synchronized (t) {
				while (!t.ready) {
					t.wait();
				}
				return t.res;
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

		return null;
	}

	TaskRunnerImpl(int threadCount) {
		threads = new Thread[threadCount];
		q = new ArrayDeque<MyTask<?, ?>>();
		for (int i = 0; i < threadCount; i++) {
			threads[i] = new Thread(new Worker(q));
			threads[i].start();
		}
	}
}
